<template>
  <template v-if="hasPermission">
    <slot></slot>
  </template>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useAuthStore } from '@/stores/modules/auth'

interface Props {
  /**
   * 权限编码，支持多个权限编码（满足其一即可）
   * @example 单个权限: 'system:user:add'
   * @example 多个权限: ['system:user:add', 'system:user:edit']
   */
  code: string | string[]
  /**
   * 权限匹配模式
   * - some: 满足其中一个权限即可(默认)
   * - every: 必须满足所有权限
   */
  mode?: 'some' | 'every'
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'some',
})

const authStore = useAuthStore()

const hasPermission = computed(() => {
  const codes = Array.isArray(props.code) ? props.code : [props.code]
  const userPermissions = authStore.permissions || []

  return props.mode === 'some'
    ? codes.some((code) => userPermissions.includes(code))
    : codes.every((code) => userPermissions.includes(code))
})
</script>
